package org.example.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.example.anno.NoAuth;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class NoAuthComponent implements BeanPostProcessor {

    public List<String> paths = new ArrayList<>();



    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Class<?> clazz = bean.getClass();
        if(clazz.isAnnotationPresent(RequestMapping.class)){
            RequestMapping re = clazz.getAnnotation(RequestMapping.class);
            for (Method method : clazz.getDeclaredMethods()) {
                if (method.isAnnotationPresent(NoAuth.class)) {
                    NoAuth noAuth = method.getAnnotation(NoAuth.class);
                    String methodPath = "";
                    if(method.isAnnotationPresent(GetMapping.class)){
                        String[] arr = method.getAnnotation(GetMapping.class).value();
                        if(arr.length > 0){
                            methodPath = arr[0];
                        }

                    }
                    if(method.isAnnotationPresent(PostMapping.class)){
                        String[] arr = method.getAnnotation(PostMapping.class).value();
                        if(arr.length > 0){
                            methodPath = arr[0];
                        }
                    }
                    if(method.isAnnotationPresent(PutMapping.class)){
                        String[] arr = method.getAnnotation(PutMapping.class).value();
                        if(arr.length > 0){
                            methodPath = arr[0];
                        }
                    }
                    if(method.isAnnotationPresent(DeleteMapping.class)){
                        String[] arr = method.getAnnotation(DeleteMapping.class).value();
                        if(arr.length > 0){
                            methodPath = arr[0];
                        }
                    }
                    if(methodPath.isEmpty()){
                        paths.add(re.value()[0]);
                    } else {
                        String s = re.value()[0] + "/" + methodPath;
                        s = s.replaceAll("//", "/");
                        paths.add(s);
                    }
                }
            }
        }
        return bean;
    }



}
